﻿#encoding: utf-8

require 'time'
require 'date'

load 'rds_api.rb'
@rds = @rds_tt

=begin
  用于将ghost blog中的文章直接复制到eb_article中
  典型用法： 
  1) 日常调用 ruby poster_man.rb 今天
  2) 指定时间 ruby poster_man.rb 2020-05-04 1 #5月4日一整天，再往后数1天
=end

eday = ARGV[0].nil? ? Date.today : Date.parse(ARGV[0])
counter = ARGV[1].nil? ? 1 : ARGV[1].to_i #默认为1，临时改30
sday = eday - counter
etime = ( Time.parse eday.strftime('%Y-%m-%d') + " 23:59:59" ).strftime('%Y-%m-%d %H:%M:%S')
stime = ( Time.parse sday.strftime('%Y-%m-%d') + " 00:00:00" ).strftime('%Y-%m-%d %H:%M:%S')

#convert static path to url
def cvtsp path
  return '' if path.nil?
  path = path.gsub('__GHOST_URL__','https://mall.totembio.cn')
  return path
end

def remove_tag html, tag
  while html.include? tag
    htmlA = html.split(tag)
    htmlb = htmlA[0] #关键字前一部分
    htmlc = html[htmlb.size+tag.size..html.size] #关键字后一部分
    htmlC = htmlc.split('"')
    htmld = htmlC[0]
    htmle = htmlc[htmld.size+1..htmlc.size] #关键字后面第一个引号后的一部分
    html = htmlb + htmle
  end
  return html
end

#post html to article html
def p2a html
  html = html.gsub('"__GHOST_URL__','"https://mall.totembio.cn')
  html = html.gsub('<iframe width=100% height=100%','<video')
  html = html.gsub('</iframe>','</video>')
  html = html.gsub('frameborder=\"0\" allowfullscreen','')
  html = html.gsub('frameborder="0" allowfullscreen','')
  html = html.gsub('<figure class="kg-card kg-image-card">','<p>')
  html = html.gsub('</figure>','</p>')
  html = html.gsub('class="kg-image">','/>')
  html = html.gsub('class="kg-image"','')
  html = remove_tag html, 'srcset="'
  html = remove_tag html, 'sizes="'
  return html
end

def update_article aid, post


  #cid比较复杂，先保持不动
  sql =  "update tutem_mall.eb_article set
      author = '图腾益生科普',
      is_hot = 1,
      title = '#{post['title']}', image_input = '#{cvtsp post['feature_image']}', synopsis = '#{post['custom_excerpt']}',
      share_title = '#{post['title']}', share_synopsis = '#{post['custom_excerpt']}',
      post_id = '#{post['id']}',
      url = ''
    where id = #{aid};"
  queryRds sql

  sql = "update tutem_mall.eb_article_content set content = '#{@rds_tt.escape p2a(post['html'])}' where nid = #{aid};"
  queryRds sql

end

#建立一个空的aid，准备替换
def create_article

  queryRds "insert into tutem_mall.eb_article(cid,title,post_id,hide,image_input,status,add_time) values(2,'','to_be_update',0,'',1,#{Time.now.to_i});"

  aid = 0
  queryRds("select max(id) as aid from tutem_mall.eb_article where post_id = 'to_be_update'").each do |query|
    aid = query['aid']
    break
  end

  queryRds "insert into tutem_mall.eb_article_content(nid,content) values(#{aid},'to_be_update');" if aid > 0
  return aid

end

#建立一个空的tid，准备替换
def create_eb_tag tag

    name = tag['name']
    ghost_id = tag['id']
    description = tag['description']
    description = '相信图腾，战胜命运' if description.nil?
    queryRds "insert into tutem_mall.eb_tag(name, ghost_id, description) values('#{@rds_tt.escape name}','#{@rds_tt.escape ghost_id}', '#{@rds_tt.escape description}');"

end

def update_eb_tag tid, tag

    description = tag['description']
    description = '相信图腾，战胜命运' if description.nil?
    sql =  "update tutem_mall.eb_tag set name = '#{@rds_tt.escape tag['name']}', description = '#{@rds_tt.escape description}' where id = #{tid};"
    queryRds sql

end

def sync_post stime, etime
  sql = "select * from tutem_blog.posts where updated_at between '#{stime}' and '#{etime}' and status = 'published';"
  queryRds(sql).each do |post|
    queryRds("select count(*) as rec, id from tutem_mall.eb_article where post_id = '#{post['id']}'").each do |article|
      aid = article['id']
      if article['rec'] > 0 
        puts "post #{post['id']} existed to update #{aid}"
      else
        puts "post #{post['id']} need to create #{aid}"
        aid = create_article
      end
      update_article(aid, post) if aid > 0
    end
  end
end

def sync_tags stime, etime

  sql = "select * from tutem_blog.tags where updated_at between '#{stime}' and '#{etime}';"
  queryRds(sql).each do |tag|
    queryRds("select count(*) as rec, id from tutem_mall.eb_tag where ghost_id = '#{tag['id']}'").each do |eb_tag|
      tid = eb_tag['id']
      if eb_tag['rec'] > 0 
        puts "tag #{tag['id']} existed to update #{tid}"
        update_eb_tag(tid, tag)
      else
        puts "tag #{tag['id']} need to create #{tid}"
        aid = create_eb_tag tag
      end
    end
  end

end

def set_weight_for_tags

    sql = "select id, ghost_id from tutem_mall.eb_tag"
    queryRds(sql).each do |r|
        tag_id = r['id']
        ghost_id = r['ghost_id'] #这个是ghost的tag_id
        #每个tag下面对应的ghost_tag_id下的所有ghost_post_id文章对应的article的阅读量
        sql2 = "select sum(visit) as weight from tutem_mall.eb_article where post_id in (select post_id from tutem_blog.posts_tags where tag_id = '#{ghost_id}')"
        weight = 0
        queryRds(sql2).each do |r2|
            weight = r2['weight']
        end
        weight = 0 if weight.nil?
        sql3 = "update tutem_mall.eb_tag set weight = #{weight} where id = #{tag_id}"
        queryRds(sql3)
    end

    sql = "update tutem_mall.eb_tag set weight = 0 where ghost_id not in (select tag_id from tutem_blog.posts_tags where post_id in (select post_id from tutem_mall.eb_article where post_id != ''))"
    queryRds sql
end

def set_posts_privilege
  sqls = []
  sqls += ["update tutem_mall.eb_article set privilege = 1 where id in (select nid from tutem_mall.eb_article_content where content like '%入组%' or content like '%招募%')"]
  sqls += ["update tutem_mall.eb_article set privilege = 1 where title like '%入组%' or title like '%招募%'"]
  sqls += ["update tutem_mall.eb_article set privilege = 1 where synopsis like '%入组%' or synopsis like '%招募%'"]
  commitTrans sqls
end

sync_post stime, etime
sync_tags stime, etime
set_weight_for_tags
set_posts_privilege
